package com.wzx.ptplatform.service.impl;

import com.wzx.ptplatform.dao.ReceivedResumeDao;
import com.wzx.ptplatform.domain.CollectMessage;
import com.wzx.ptplatform.domain.ReceivedResume;
import com.wzx.ptplatform.service.ReceivedResumeService;
import com.wzx.ptplatform.utils.PtplatformException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import java.util.List;

/**
 * @author 紫煦桉
 */
@Service
public class ReceivedResumeServiceImpl implements ReceivedResumeService {

    @Resource
    private ReceivedResumeDao receivedResumeDao;

    @Override
    public Page<ReceivedResume> findList(ReceivedResume receivedResume, Integer page, Integer limit) throws PtplatformException {
        Specification<ReceivedResume> spec = (Specification<ReceivedResume>) (root, criteriaQuery, criteriaBuilder) -> {
            Predicate predicate = criteriaBuilder.conjunction();
            List<Expression<Boolean>> exList = predicate.getExpressions();//动态SQL表达式集合
            if (receivedResume.getStudent() != null && receivedResume.getStudent().getStudentName() != null) {
                exList.add(criteriaBuilder.like(root.get("student").get("studentName").as(String.class), "%" + receivedResume.getStudent().getStudentName() + "%"));
            }
            if (receivedResume.getCompany() != null && receivedResume.getCompany().getCompanyName() != null) {
                exList.add(criteriaBuilder.like(root.get("company").get("companyName").as(String.class), "%" + receivedResume.getCompany().getCompanyName() + "%"));
            }
            return predicate;
        };
        PageRequest pageable = PageRequest.of(page, limit, Sort.Direction.DESC, "id");
        return receivedResumeDao.findAll(spec, pageable);
    }

    @Override
    public ReceivedResume findById(long id) throws PtplatformException {
        return receivedResumeDao.findById(id).orElse(null);
    }

    @Override
    public boolean deleteById(long id) throws PtplatformException {
        try {
            receivedResumeDao.deleteById(id);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean saveOrEdit(ReceivedResume receivedResume) throws PtplatformException {
        try {
            receivedResumeDao.saveAndFlush(receivedResume);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
